import { reqUserRegister, reqCode, reqLogin, reqUserInfo } from '@/api'
import { setToken, getToken } from '@/utils/userAbout'

export default {
  state: {
    code: '',
    token: getToken(),
    userInfo: {},
  },
  mutations: {
    UPDATE_CODE(state, code) {
      state.code = code
    },
    UPDATE_TOKEN(state, token) {
      state.token = token
    },
    UPDATE_USERINFO(state, userInfo) {
      state.userInfo = userInfo
    },
  },
  actions: {
    // 注册
    async getUserInfo({ commit }, userInfo) {
      let result = await reqUserRegister(userInfo)
      if (result.code === 200) {
        return 'ok'
      } else {
        return Promise.reject('fail')
      }
    },
    // 获取验证码
    async getCode({ commit }, phone) {
      let result = await reqCode(phone)
      if (result.code === 200) {
        commit('UPDATE_CODE', result.data)
        return 'ok'
      } else {
        return Promise.reject('fail')
      }
    },
    // 登录
    async getLogin({ commit }, userInfo) {
      let result = await reqLogin(userInfo)
      if (result.code === 200) {
        commit('UPDATE_TOKEN', result.data.token)
        setToken(result.data.token)
        return 'ok'
      } else {
        return Promise.reject('fail')
      }
    },
    // 获取用户信息
    async getUserInfo({ commit }) {
      let result = await reqUserInfo()
      console.log(result)
      if (result.code === 200) {
        commit('UPDATE_USERINFO', result.data)
        return 'ok'
      } else {
        return Promise.reject('fail')
      }
    },
  },
  getters: {},
}
